<template>
  <div class="form-area">
    <!--表单类型-->
    <el-form v-if="formDatas.showType==='form'"
             :model="curDatas"
             :rules="rules"
             ref="form"
             class="row"
             :class="editFlag?'form-edit':'form-static'"
             :hide-required-asterisk="!editFlag">
      <el-form-item v-for="(item,i) in fields"
                    :key="item.fieldCode+i"
                    :prop="item.fieldCode"
                    :class="['col-md-'+item.scale,item.emptyScale>0?'col-mr-'+item.emptyScale:'',item.editType==='relevanceForm'?'item-relevance-'+item.relevanceForm.showType:'']">
        <span slot="label">{{item.fieldName}}<el-tooltip v-if="!$isEmpty(item.tips)&&item.editType!='upload'" class="item" effect="dark" :content="item.tips" placement="top"><i class="el-icon-info"></i></el-tooltip>:</span>
        <!--显示-->
        <table-item v-if="itemDisplayType(item)==='show-table'" :params="params" :formDatas="item.relevanceForm" ></table-item>
        <row-item v-if="itemDisplayType(item)==='show-row'" :params="params" :formDatas="item.relevanceForm" ></row-item>
        <form-item v-else-if="itemDisplayType(item)==='show-item'" :item="item"></form-item>
        <form-components v-else-if="itemDisplayType(item)==='show-form'" :formDatas="item.relevanceForm" :editFlag=false :params="params"></form-components>
        <!--编辑-->
        <table-edit v-else-if="itemDisplayType(item)==='edit-table'" :params="params" :formDatas="item.relevanceForm" :addBtnShow="addBtnShow"></table-edit>
        <row-item-edit v-else-if="itemDisplayType(item)==='edit-row'" :params="params" :formDatas="item.relevanceForm" :addBtnShow="addBtnShow"></row-item-edit>
        <!--<select-input-edit v-else-if="item.editType==='selectInput'"  :item="item" :curDatas.sync="curDatas" :curRules.sync="rules"></select-input-edit>
-->
        <form-components v-else-if="itemDisplayType(item)==='edit-form'" :formDatas="item.relevanceForm" :editFlag=true :params="params"></form-components>
        <form-item-edit v-else-if="itemDisplayType(item)==='edit-item'" :item="item" :curDatas.sync="curDatas"></form-item-edit>
      </el-form-item>

      <!--按钮-->
      <div class="form-ft" v-if="editFlag&&btnsShow">
        <a class="btn-theme" @click="submitForm()">{{submitText}}</a>
        <a class="btn-theme-o ml20" v-if="cancelBtnShow" @click="cancelForm()">取消</a>
        <a class="btn-theme-o ml20" v-if="resetBtnShow" @click="resetForm()">重置</a>
      </div>

      <!--<div style="clear: both"><hr>curDatas:{{curDatas}}</div>-->
    </el-form>

    <!--表格类型-->
    <div class="show-type-table" v-else-if="formDatas.showType==='table'">
      <!--显示-->
      <table-item v-if="!editFlag" :formDatas="formDatas" :params="params"></table-item>
      <!--编辑-->
      <table-edit v-else :formDatas="formDatas" :params="params" :addBtnShow="addBtnShow"></table-edit>
    </div>

    <!--row类型-->
    <div class="show-type-row" v-else-if="formDatas.showType==='row'">
      <!--显示-->
      <row-item v-if="!editFlag" :formDatas="formDatas" :params="params"></row-item>
      <!--编辑-->
      <row-item-edit v-else :formDatas="formDatas" :params="params" :addBtnShow="addBtnShow">
      </row-item-edit>
    </div>
  </div>
</template>

<script>
import FormItem from "./FormItem";
import FormItemEdit from "./FormItemEdit";
import TableEdit from "./TableEdit";
//import SelectInputEdit from "./SelectInputEdit";
import TableItem from "./TableItem";
import RowItem from "./RowItem";
import RowItemEdit from "./RowItemEdit";

function defaultFn() {
  return true;
}

export default {
  name: "FormComponents",
  components: {
    RowItemEdit,
    RowItem,
    TableItem,
    //SelectInputEdit,
    FormItem,
    FormItemEdit,
    TableEdit
  },
  props: {
    formDatas: {
      required: true
    },
    editFlag: {
      type: Boolean,
      default: true
    },
    //要传的参数
    params: {
      type: Object
    },
    btnsShow: {
      type: Boolean,
      default: true
    },
    //取消按钮是否显示
    cancelBtnShow: {
      type: Boolean,
      default: true
    },
    submitText: {
      type: String,
      default: "提交"
    },
    onSubmit: {
      type: Function
      /* default: () => {},*/
    },
    resetBtnShow: {
      type: Boolean,
      default: false
    },
    onSuccess: {
      type: Function,
      default: defaultFn
    },
    onError: {
      type: Function,
      default: defaultFn
    },
    addBtnShow: {
      type: Boolean,
      default: true
    },
    onlyEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      editableCodes: [],
      curDatas: {},
      rules: {},
      showType: "",
      tableDatas: {},
      totalCount: 0,
      addFlag: false,
      reload: false
    };
  },
  computed: {
    fields: function() {
      return this.formDatas.fields.filter(item => {
        if (this.onlyEdit) {
          return !item.hidden && item.editable;
        } else {
          return !item.hidden;
        }
      });
    }
  },
  watch: {
    formDatas: {
      handler(curVal) {
        this.init(curVal);
        this.showType = curVal.showType;
      },
      deep: true
    }
  },
  methods: {
    init(curVal) {
      if (curVal.showType === "table" || curVal.showType === "row") {
        //this.getTableData(curVal.tableDataUrl);
      }
      let fields = curVal.fields;
      for (let item of fields) {
        let value = item.defaultValue;
        this.$set(this.rules, item.fieldCode, item.rules);
        if (curVal.showType != "table" && curVal.showType != "row") {
          //数组类型的逗号转数组
          if (["upload", "cascader", "checkbox"].includes(item.editType)) {
            value = this.$isEmpty(value) ? [] : value.split(",");
          }
          if (item.editType != "relevanceForm") {
            this.$set(this.curDatas, item.fieldCode, value);
          }
          if (item.editable) {
            this.editableCodes.push(item.fieldCode);
          }
        }
      }
    },
    itemDisplayType(item) {
      let isEdit = this.editFlag && item.editable;
      if (isEdit) {
        //编辑状态
        if (item.editType === "relevanceForm") {
          //关联表单
          return "edit-" + item.relevanceForm.showType;
        } else {
          return "edit-item";
        }
      } else {
        //显示状态
        if (item.editType === "relevanceForm") {
          return "show-" + item.relevanceForm.showType;
        } else {
          return "show-item";
        }
      }
    },
    //表单类型-保存
    submitForm(saveUrl = this.formDatas.saveUrl) {
      this.$refs["form"].validate(valid => {
        this.$emit("validate", valid);
        Object.assign(this.curDatas, this.params);
        let data = JSON.parse(JSON.stringify(this.curDatas));
        for (let key in data) {
          if (data[key] instanceof Array) {
            //数组类型的逗号转换
            data[key] = data[key].join(",");
          }
        }
        if (valid) {
          if (typeof this.onSubmit !== "undefined") {
            this.onSubmit();
          } else {
            let params = this.$qs.stringify(data);
            this.$http.post(saveUrl, params).then(
              res => {
                if (res.code === 0) {
                  this.$emit("update:editFlag", false);
                  this.$emit("reloadData"); //添加成功后重置表单
                  if (this.onSuccess(res)) {
                    //如果默认的，返回true
                    this.$message.success(res.msg);
                  }
                } else {
                  if (this.onError(res)) {
                    this.$message.warning(res.msg);
                  }
                }
              },
              err => {
                this.$message.error(err.msg);
              }
            );
          }
        } else {
          return false;
        }
      });
    },
    //表单类型-取消
    cancelForm() {
      this.$emit("update:editFlag", false);
      /*      if (["table", "row"].includes(this.showType)) {
				this.newList = [];
				this.submitDatas = JSON.parse(JSON.stringify(this.tableDatas));
			  } else {
				this.$refs[formName].resetFields();
			  }*/
    },
    //验证表单
    validateForm() {
      this.$refs["form"].validate(flag => {
        this.$emit("validate", flag);
        if (flag) {
          let editableDatas = {};
          for (let key of this.editableCodes) {
            let data = this.curDatas[key];
            if (data instanceof Array) {
              data = data.join(",");
            }
            editableDatas[key] = data;
          }
          this.$emit("editableDatas", editableDatas);
          this.$emit("allFormDatas", this.curDatas);
        }
      });
    },
    //重置表单
    resetForm() {
      this.$refs["form"].resetFields();
    }
  }
};
</script>
